package com.mexcad.db.utils;

import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

import com.mexcad.db.connectors.SolicitudConnector;
import com.mexcad.db.delegate.DelegateConnectors;
import com.mexcad.db.dto.Solicitud;
import com.mexcad.utils.Constantes;

// Send a simple, single part, text/plain e-mail
public class CorreoElectronico {

    private String to ;  
   /* private String from="";
    private String pass="";
    private String host = "smtp.gmail.com";
    */
    /*
    private String from="mexcad@mexcad.com.mx";
    private String pass="microtek";
    private String host = "mail.mexcad.com.mx";
    */
    
    private String from="cotizaciones@mexcad.com.mx";
    private String pass="mje3xscdaqde10";
    private String host = "mail.mexcad.com.mx";

    private String message;
	private String subject;
	private static final String PUERTO="26"; //"587" //26
	
	public final static String MAIL_SMTP_HOST="mail.smtp.host";
	public final static String MAIL_SMTP_AUTH="mail.smtp.auth";
	
	
	public final static String MAIL_SMTP_STARTTLS_ENABLE="mail.smtp.starttls.enable";
	
	public CorreoElectronico() {}
	public CorreoElectronico(String to, String subject, String message) {
		this.to=to;
		this.subject=subject;
		this.message=message;
		
	}

	public void enviaCorreo()throws MessagingException{
		if(to!=null){
			System.setProperty("mail.mime.charset","Cp1252");	
		  Properties props = new Properties();
		  /*
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.port",PUERTO );
			props.put("mail.smtp.auth", "true");
		  */
		  
		  props.put(CorreoElectronico.MAIL_SMTP_HOST,host );
		  props.put("mail.smtp.port", PUERTO);
		  props.put(CorreoElectronico.MAIL_SMTP_AUTH,"true");
		  
		  
		  Authenticator auth = new SMTPAuthenticator( from, pass );

		  Session session = Session.getInstance(props, auth);
		  
		  try {
		    	 
			  Message msg = new MimeMessage(session);
			  
			  msg.setFrom(new InternetAddress(from));
	          InternetAddress[] address = {new InternetAddress(to) };
	          msg.setRecipients(Message.RecipientType.TO, address);
	          //(Message.RecipientType.TO, address);
	          
	          msg.setSubject(subject!=null?subject:"");
	          msg.setSentDate(new Date());

	          
	        //  msg.setText();
	          msg.setContent(message!=null?message:"", "text/html");
	          Transport trans = session.getTransport(address[0]);
	          
	          trans.connect(this.host,this.from);
	          //trans.send(msg);
	          trans.sendMessage(msg,address);

		          
		   }catch (MessagingException mex) {
		         
		          mex.printStackTrace();
		          System.out.println(mex.getLocalizedMessage());
		          throw mex;
		   }
			
			
		}
	}
	
	public void enviaCorreoConContrato(int id)throws MessagingException{
		if(to!=null){
		  System.setProperty("mail.mime.charset","Cp1252");
		  Properties props = new Properties();
		/*
		  	props.put("mail.smtp.host", host);
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.port",PUERTO );
			props.put("mail.smtp.auth", "true");
		*/
		  
		  props.put(CorreoElectronico.MAIL_SMTP_HOST,host );
		  props.put("mail.smtp.port", PUERTO);
		  props.put(CorreoElectronico.MAIL_SMTP_AUTH,"true");
		  
		  Authenticator auth = new SMTPAuthenticator( from, pass );

		  Session session = Session.getInstance(props, auth);
		  String archivo=null;
		  
		  archivo= new ArchivoContrato().getContratoById(archivo, id);
		  
		  try {
		    	 
			  Message msg = new MimeMessage(session);
			  
			  msg.setFrom(new InternetAddress(from));
	          InternetAddress[] address = {new InternetAddress(to) };
	          msg.setRecipients(Message.RecipientType.TO, address);
	          //(Message.RecipientType.TO, address);
	          
	          msg.setSubject(subject!=null?subject:"");
	          msg.setSentDate(new Date());


		          MimeMultipart multipart = new MimeMultipart("related");
	
		         
		          BodyPart messageBodyPart = new MimeBodyPart();
		          String htmlText = message;
		          messageBodyPart.setContent(htmlText, "text/html");
	
		          // add it
		          multipart.addBodyPart(messageBodyPart);
		          
		          // second part (the image)
		          messageBodyPart = new MimeBodyPart();
		          DataSource fds = new FileDataSource(Constantes.RUTA_CONTRATOS+archivo+id+".pdf");
		          messageBodyPart.setDataHandler(new DataHandler(fds));
		          messageBodyPart.setFileName(archivo+id+".pdf");
		          messageBodyPart.setHeader("Content-ID","<image>");
	
		          // add it
		          multipart.addBodyPart(messageBodyPart);
	
		          // put everything together
		          msg.setContent(multipart);
		          Transport trans = session.getTransport(address[0]);
		          
		          trans.connect();
		    
		          trans.sendMessage(msg,address);



		          
		   }catch (MessagingException mex) {
		         
		          mex.printStackTrace();
		          System.out.println(mex.getLocalizedMessage());
		          throw mex;
		   }
			
			
		}
	}
	
	
	
	
	
  public static void main(String[] args) {
	  String mensaje = "<H1>Hello</H1>" + 
	  "";

	  for(int i=0;i<5;++i){
		  CorreoElectronico email = new CorreoElectronico("efrenm@gmail.com","PRUEBA DE CORREO mexcad", mensaje +i );
		  try {
			email.enviaCorreo();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  }
	  System.out.println("Correo enviado");
 
    
  }
public static int enviarCotizacion(int id, boolean reenvio) {
	Solicitud sol = DelegateConnectors.getSolicitudPorId(id);
	String html ="<img src=\"http://www.mexcad.com.mx/Mexcad.jpg\" width=\"182\" height=\"112\">";
	html+=SolicitudConnector.getHTMLStringfromSolicitud(sol);
	
	 CorreoElectronico email = new CorreoElectronico(DelegateConnectors.getEjecutivoPorId(sol.getIdEjecutivo()).getEmail(),"Cotizaci�n de "+sol.getApellidoPaterno()+" "+sol.getApellidoMaterno()+" " + sol.getNombresSolicitante(), html );
	 if(!reenvio){
		
	 	DelegateConnectors.actualizaStatusSolicitud(sol,SolicitudConnector.ENVIO_CONTRATO);	
	 }
	 try {
		email.enviaCorreo();
	} catch (MessagingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return -1;
	}
	return 0;
	
	
}

public static int enviarCotizacionConContrato(int id, boolean reenviar) {
	Solicitud sol = DelegateConnectors.getSolicitudPorId(id);

	String html ="<img src=\"http://www.mexcad.com.mx/Mexcad.jpg\" width=\"182\" height=\"112\">";
	
	html+=SolicitudConnector.getHTMLStringfromSolicitudDesglose(sol);
	if(!reenviar){

	 DelegateConnectors.actualizaStatusSolicitud(sol,SolicitudConnector.AUTORIZACION_CREDITO);	
	}
	 CorreoElectronico email = new CorreoElectronico(DelegateConnectors.getEjecutivoPorId(sol.getIdEjecutivo()).getEmail(),"Contrato de "+sol.getApellidoPaterno()+" "+sol.getApellidoMaterno()+" " + sol.getNombresSolicitante(), html );
	 try {
		email.enviaCorreoConContrato(id);
	} catch (MessagingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return -1;
	}
	return 0;
	
	
}

}//End of class


class SMTPAuthenticator extends Authenticator{
	
	private String userName;
	private String password;
	
	SMTPAuthenticator(String userName, String password) {
		this.userName=userName;
		this.password=password;
	}
	
	public PasswordAuthentication getPasswordAuthentication(){
		
		return new PasswordAuthentication(this.userName,this.password);
	}
	
}
